package com.sanhe.rfmuscle.fragment;

import static com.menu.app.util.FunctionCode.START1;
import static com.menu.app.util.FunctionCode.START2;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.menu.app.util.port.SerialManage;
import com.plata.base.aclr.common.SilentTask;
import com.plata.base.aclr.common.TaskEngine;
import com.sanhe.rfmuscle.R;
import com.sanhe.rfmuscle.bean.ParamBean;
import com.sanhe.rfmuscle.databinding.FragmentBodyBinding;
import com.sanhe.rfmuscle.event.Event;
import com.sanhe.rfmuscle.util.Const;
import com.sanhe.rfmuscle.util.ParamHelper;
import com.sanhe.rfmuscle.view.PointView;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.support.toast.ToastUtil;
import taylor.lib.framesurfaceview.FrameSurfaceView;

public class BodyFragment extends BaseWorkFragment {
    private static final String TAG = "BodyFragment";

    FragmentBodyBinding binding;
    private boolean front = true;
    private ArrayList<PointView> viewList = new ArrayList<>();

    @SuppressLint("ClickableViewAccessibility")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = FragmentBodyBinding.inflate(inflater, container, false);

        viewList.add(binding.leftUpper);// 左上臂
        viewList.add(binding.rightUpper);// 右上臂
        viewList.add(binding.leftForearm);// 左小臂
        viewList.add(binding.rightForearm);// 右小臂
        viewList.add(binding.abdomen);// 腹部
        viewList.add(binding.leftThigh);// 左大腿
        viewList.add(binding.rightThigh);// 右大腿
        viewList.add(binding.leftShin);// 左小腿
        viewList.add(binding.rightShin);// 右小腿
        viewList.add(binding.leftUpperBack);// 左上臂（背部）
        viewList.add(binding.rightUpperBack);// 右上臂（背部）
        viewList.add(binding.leftForearmBack);// 左小臂（背部）
        viewList.add(binding.rightForearmBack);// 右小臂（背部）
        viewList.add(binding.back);// 背部
        viewList.add(binding.leftThighBack);// 左大腿（背部）
        viewList.add(binding.rightThighBack);// 右大腿（背部）
        viewList.add(binding.leftShinBack);// 左小腿（背部）
        viewList.add(binding.rightShinBack);// 右小腿（背部）
        for (int i = 0; i < viewList.size(); i++) {
            final int i2 = i + 1;
            viewList.get(i).setonPointClickListener((view, index) -> {
                switch (index) {
                    case 0:
                        initSelect();
                        ParamBean bean = ParamHelper.getParam(i2);
                        if (bean == null) {
                            ToastUtil.showShortToast(getActivity(), "NO DATA");
                            return;
                        }
                        showLoading();
                        sendParam(bean);
                        break;
                    case 1:
                        ParamHelper.saveParam(i2);
                        break;
                    case 2:
                        ParamHelper.removeParam(i2);
                        break;
                }
            });
        }

        binding.turnBack.setOnClickListener(v -> {
            turnBack();
        });
        binding.turnFront.setOnClickListener(v -> {
            turnFront();
        });
        binding.turnFront.setImageResource(R.mipmap.body_turn_front_press);
        binding.body.setOnClickListener(v -> initLongSelect());
        binding.body.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        return binding.getRoot();
    }

    private void sendParam(ParamBean bean) {
        TaskEngine.getInstance().submit(new SilentTask("") {
            @Override
            public void runInBackground() throws Exception {
                Thread.sleep(200);
                //切换time1
                try {
                    int p = bean.getTime1();
                    Log.e(TAG, "切换time1: " + p);
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 6, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(200);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换time2
                try {
                    int p = bean.getTime2();
                    Log.e(TAG, "切换time2: " + p);
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 7, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(200);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换flow1
                try {
                    int p = bean.getFreq1();
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 0, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(200);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                //切换flow2
                try {
                    int p = bean.getFreq2();
                    byte[] tmp = {START1, START2, 6, (byte) 0x83, 0x11, 5, 1, 0, (byte) p};
                    SerialManage.getInstance().send(tmp);
                    Thread.sleep(200);
                } catch (Throwable e) {
                    e.printStackTrace();
                }
                if (Const.mode == 1) {
                    //切换level
                    try {
                        int level = bean.getLevel();
                        if (level == 1) {
                            sendTouchEvent((byte) 0, (byte) 0x80);
                        } else if (level == 2) {
                            sendTouchEvent((byte) 0, (byte) 0x81);
                        } else if (level == 3) {
                            sendTouchEvent((byte) 0, (byte) 0x82);
                        }
                        Thread.sleep(200);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                if (Const.mode == 2) {
                    //切换rf1
                    try {
                        int target = bean.getRf1();
                        int rf = Event.leftRfEvent.getValue();
                        if (target < rf){
                            for (int i = 0; i < rf - target; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x92);
                                Thread.sleep(200);
                            }
                        } else if (target > rf){
                            for (int i = 0; i < target - rf; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x93);
                                Thread.sleep(200);
                            }
                        }

                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换rf2
                    try {
                        int target = bean.getRf2();
                        int rf = Event.rightRfEvent.getValue();
                        if (target < rf){
                            for (int i = 0; i < rf - target; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x90);
                                Thread.sleep(200);
                            }
                        } else if (target > rf){
                            for (int i = 0; i < target - rf; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x91);
                                Thread.sleep(200);
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    //切换level
                    try {
                        int target = bean.getLevel();
                        int level = Event.workingModeEvent.getValue();
                        if (target < level){
                            for (int i = 0; i < level - target; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x26);
                                Thread.sleep(200);
                            }
                        } else if (target > level){
                            for (int i = 0; i < target - level; i++) {
                                sendTouchEvent((byte) 0, (byte) 0x27);
                                Thread.sleep(200);
                            }
                        }
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                }
                h.post(() -> hideLoading());
            }
        });
    }

    private void initSelect() {
        for (int i = 0; i < viewList.size(); i++) {
            viewList.get(i).cancelSelect();
        }
    }

    private void turnBack() {
        if (front) {
            binding.frontGroup.setVisibility(View.INVISIBLE);
            binding.backGroup.setVisibility(View.INVISIBLE);
            binding.turnFront.setEnabled(false);
            binding.turnBack.setEnabled(false);
            binding.turnBack.setImageResource(R.mipmap.body_turn_back_press);
            binding.turnFront.setImageResource(R.mipmap.body_turn_front);
            binding.anim.post(animStart);
        }
    }

    private void turnFront() {
        if (!front) {
            binding.frontGroup.setVisibility(View.INVISIBLE);
            binding.backGroup.setVisibility(View.INVISIBLE);
            binding.turnFront.setEnabled(false);
            binding.turnBack.setEnabled(false);
            binding.turnBack.setImageResource(R.mipmap.body_turn_back);
            binding.turnFront.setImageResource(R.mipmap.body_turn_front_press);
            binding.anim.post(animStart);
        }
    }

    //顺时针动画
    Runnable animStart = new Runnable() {
        @Override
        public void run() {
            if (front) {
                front = false;
                buildToBackAnim();
            } else {
                front = true;
                buildToFrontAnim();
            }

        }
    };

    private void buildToBackAnim() {
        List<String> tmp = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            tmp.add("b00" + i);
        }
        for (int i = 10; i < 61; i++) {
            tmp.add("b0" + i);
        }
        List<Integer> list = new ArrayList<>();
        for (String s : tmp) {
            list.add(com.menu.app.util.Utils.getResourceByName(s));
        }
        binding.anim.setBitmapIds(list);
        binding.anim.setDuration(list.size() * 25);
        binding.anim.setRepeatTimes(0);

        binding.anim.setFrameAnimListener(new FrameSurfaceView.FrameAnimListener() {
            @Override
            public void onAnimEnd() {
                Log.e(TAG, "onAnimEnd: buildToBackAnim");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.backGroup.setVisibility(View.VISIBLE);
                        binding.turnFront.setEnabled(true);
                        binding.turnBack.setEnabled(true);
                        binding.anim.destroy();
                    }
                });

            }

            @Override
            public void onAnimProgress(int current, int total) {
                if (current == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.body.setVisibility(View.INVISIBLE);
                        }
                    });
                } else if (total - current == 2) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.body.setImageResource(R.mipmap.b060);
                            binding.body.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        });
        if (!binding.anim.isStart()) {
            binding.anim.start();
        }
    }

    private void buildToFrontAnim() {
        List<String> tmp = new ArrayList<>();
        for (int i = 61; i < 100; i++) {
            tmp.add("b0" + i);
        }
        for (int i = 100; i < 121; i++) {
            tmp.add("b" + i);
        }
        List<Integer> list = new ArrayList<>();
        for (String s : tmp) {
            list.add(com.menu.app.util.Utils.getResourceByName(s));
        }
        binding.anim.setBitmapIds(list);
        binding.anim.setDuration(list.size() * 25);
        binding.anim.setRepeatTimes(0);
        binding.anim.setFrameAnimListener(new FrameSurfaceView.FrameAnimListener() {
            @Override
            public void onAnimEnd() {
                Log.e(TAG, "onAnimEnd: buildToFrontAnim");
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        binding.frontGroup.setVisibility(View.VISIBLE);
                        binding.turnFront.setEnabled(true);
                        binding.turnBack.setEnabled(true);
                        binding.anim.destroy();
                    }
                });
            }

            @Override
            public void onAnimProgress(int current, int total) {
                if (current == 1) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.body.setVisibility(View.INVISIBLE);
                        }
                    });
                } else if (total - current == 3) {
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            binding.body.setImageResource(R.mipmap.b001);
                            binding.body.setVisibility(View.VISIBLE);
                        }
                    });
                }
            }
        });
        if (!binding.anim.isStart()) {
            binding.anim.start();
        }
    }

    private void initLongSelect() {
        for (int i = 0; i < viewList.size(); i++) {
            viewList.get(i).cancelLongSelect();
        }
    }

}